import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 在模块被加载的时候提前登录👌
server = smtplib.SMTP(host='smtp.qq.com', port=587)
server.login("zjueman@qq.com", 'ocitvfwbtgyacaag')

def send_email(name, email, file_path):
  msg = MIMEMultipart()
  msg['subject'] = f"欢迎你，{name}"
  msg['from'] = "zjueman@qq.com"
  msg['to'] = email

  # 定义HTML页面的内容
  html_content = f"""\
  <html>
    <body>
      <p>你好，{name}<br>
        <b>欢迎参加麦叔演唱会，请在附件中查收您的门票！</b><br>
        点这里了解更多：<a href="http://www.maishu.com">演唱会主页</a> 
      </p>
    </body>
  </html>
  """

  # 创建MIMEText的时候，用第二个参数指明这是html
  html_part = MIMEText(html_content, 'html')
  msg.attach(html_part)

  with open(file_path, 'rb') as f:
      part = MIMEApplication(f.read())
      # 用斜杠把file_path分割成多份，取最后一份就是文件名
      filename = file_path.split("/")[-1]
      part.add_header('Content-Disposition', 'attachment', filename=filename)
      msg.attach(part)

      # 在函数中直接发送，不用登录
      server.send_message(msg)

      # 也不要退出，所以注释掉下面的退出代码
      #server.quit()


if __name__ == '__main__':
  send_email('张三1', 'zjueman@qq.com', 'letters/1/张三1.docx')
